package com.example.aop.controller;

import com.example.aop.tester.MyAopInterfaceTester;
import com.example.aop.tester.MyAopTester;
import com.example.aop.tester.MyArgs;
import com.example.aop.tester.MyReturn;
import com.example.common.service.TestService;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanExpressionException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.support.DefaultSingletonBeanRegistry;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Service;

@Service
public class TestController implements BeanFactoryAware, TestService {

    private BeanFactory beanFactory;

    private DefaultSingletonBeanRegistry defaultSingletonBeanRegistry;

    @Override
    public void setBeanFactory(@NonNull BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
        if (beanFactory instanceof DefaultSingletonBeanRegistry defaultSingletonBeanRegistry) {
            this.defaultSingletonBeanRegistry = defaultSingletonBeanRegistry;
        }else {
            throw new BeanExpressionException("");
        }
    }

    @Override
    public Object doTest(Object param) {
        return doTest();
    }

    private MyReturn doTest(){
        defaultSingletonBeanRegistry.destroySingleton("myAopInterfaceTesterImpl");
        defaultSingletonBeanRegistry.destroySingleton("myAopTester");
        MyAopInterfaceTester myAopInterfaceTester = beanFactory.getBean("myAopInterfaceTesterImpl", MyAopInterfaceTester.class);
        MyAopTester myAopTester = beanFactory.getBean("myAopTester", MyAopTester.class);
        MyArgs myArgs = new MyArgs();
        myArgs.setAge(17);
        myArgs.setName("测试1");
        MyReturn myReturn;
        try{
            myReturn = myAopTester.myMethodWithThrow(myArgs);
        }catch (Throwable e){
        }
        myArgs.setName("测试2");
        myReturn = myAopTester.myMethod(myArgs);

        myArgs.setName("测试4");
        myReturn = myAopInterfaceTester.myMethod(myArgs);
        return myReturn;
    }

}
